""" Find files/stuff by certain Preds """

from glob import glob
import os,fnmatch
from path import path

class Pred:
    def accept(self,path):
        """ return True if passes this Pred """
    
class Source:
    def get(self, prevfiles):
        """ return a seq of pathnames """


class Glob(Source):
    def __init__(self, pat):
        self.pat = pat
    def get(self,prevfiles):
        return glob(self.pat)

class Walk(Source):
    def __init__(self, *roots):
        self.roots = roots
    def get(self,prevfiles):
        roots = [path(p).expanduser() for p in self.roots]
        if not roots:
            roots = prevfiles
        for r in roots:
            for f in r.walk():
                yield f

class HasPat(Pred):
    def __init__(self,*pats):
        self.pats = pats
        
    def accept(self,path):
        if not path.isdir():
            return False
        
        for p in self.pats:
            if path.glob(p):
                return True
        return False

class HasRelative(Pred):
    def __init__(self,*rels):
        self.rels = rels
    def accept(self,path):
        p = path(path)
        for r in self.rels:
            if p / r:
                return True
        return False
            
class Print(Pred):
    def accept(self,path):
        print "p",path
        return True
            
def seek(*Preds):
    paths = set()
    for r in Preds:
        if isinstance(r,Source):
            paths.update(r.get(paths))
        elif isinstance(r,Pred):
            dels = set()
            for p in paths:
                if not r.accept(p):
                    dels.add(p)
            paths -= dels
    return paths
                
        
def test():
    print seek(Walk('..'), HasPat('.svn/READ*'),Print(), HasPat('set*'))
    
test()
